package com.zk.algorithm.dynamicprogramming;

/**
 * 最长回文子串
 *
 * Input: "babad"
 * Output: "bab"
 * Note: "aba" is also a valid answer.
 *
 * @author zk
 */
public class LongestPalindromicSubstring {

    private int lo, maxLen;

    /**
     * 思路从每个字符开始，逐渐往两边扩展
     *
     * @param s
     * @return
     */
    public String longestPalindrome(String s) {
        int len = s.length();

        if (len < 2)
            return s;

        for (int i = 0; i < len - 1; i++) {
            extendPalindrome(s, i, i);  //assume odd length, try to extend Palindrome as possible
            extendPalindrome(s, i, i + 1); //assume even length.
        }

        return s.substring(lo, lo + maxLen);
    }

    private void extendPalindrome(String s, int j, int k) {
        while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) {
            j--;
            k++;
        }

        // a b b c c d
        // ↑         ↑
        // k(1)      j(6)
        //   k - j - 1 = 4
        if (maxLen < k - j - 1) {
            lo = j + 1;
            maxLen = k - j - 1;
        }
    }

}
